//
//  EJSGoodsListViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/25.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSGoodsListViewController.h"
#import "EJSGoodsDetailInfoViewController.h"

#import "EJSSegmentedControl.h"
#import "EJSGoodsCCell.h"
#import "EJSSearchGoodsRequest.h"
#import "EJSGoodsListRequest.h"
#import "EJSCategoryModel.h"
#import "XOPlatformCategoryModel.h"
#import "EJSGoodsDetailInfoRequest.h"
#import "EJSGoodsAddCartRequest.h"
#import "EJSSelectGoodsSpecView.h"
#import "EJSHomeGoodCollectionViewCell.h"
#import "EJSShoppingCartListRequest.h"

@interface EJSGoodsListViewController ()<EJSSegmentedControlDelegate, EJSEJSGoodsCCellDelegate, EJSHomeGoodCollectionViewCellDelegate>{
    UIButton *_currentSelectButton;
    NSString *_order;//onsaleDesc上架时间逆序  onsaleAsc上架时间顺序 priceAsc价格顺序 priceDesc价格逆序
    NSString *_categoryId;//子分类当前选择的id
    NSString *_sortId;//平台子分类当前选择的id
    NSInteger _currentPage;
}
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet EJSSegmentedControl *segmentedControl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *segmentedControlHeight;


@property (weak, nonatomic) IBOutlet UIButton *defaultButton;
@property (weak, nonatomic) IBOutlet UIButton *salesButton;
@property (weak, nonatomic) IBOutlet UIButton *priceButton;
@property (weak, nonatomic) IBOutlet UIImageView *priceAscImageView;
@property (weak, nonatomic) IBOutlet UIImageView *priceDescImageView;
@property (weak, nonatomic) IBOutlet UIButton *onSaleButton;
@property (weak, nonatomic) IBOutlet UIImageView *onSaleTimeAscImageView;
@property (weak, nonatomic) IBOutlet UIImageView *onSaleDescImageView;


@property (strong, nonatomic) NSMutableArray *goodsList;
@property (strong, nonatomic) EJSGoodsSkuModel *selectSkuModel;

@property (strong, nonatomic) EJSShoppingCartListModel *shoppingCartListModel;

@end

@implementation EJSGoodsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self filterActin:self.defaultButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([EJSUserModel userModel]) {
        [self getCartList];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configOwnViews{
    if(_keyWord){
        self.title = _keyWord;
        _segmentedControlHeight.constant = 0;
    }
    if(_categoryModel){
        self.title = _categoryModel.categoryName;
        if(_categoryModel.sons.count == 0){
            _segmentedControlHeight.constant = 0;
        }else{
            NSMutableArray *categoryTitles = [NSMutableArray array];
            [categoryTitles addObject:@"全部"];
            for (int index = 0; index < _categoryModel.sons.count; index ++)
            {
                EJSCategoryModel *category = _categoryModel.sons[index];
                
                [categoryTitles addObject:category.categoryName?category.categoryName:@""];
            }
            [self.segmentedControl setCategoryTitles:categoryTitles];
            self.segmentedControl.selectedIndex = 0;
        }
        _categoryId = _categoryModel.categoryId;
    }
    if(_platformCategoryModel){
        self.title = _platformCategoryModel.sortName;
        if(_platformCategoryModel.sons.count == 0){
            _segmentedControlHeight.constant = 0;
        }else{
            NSMutableArray *categoryTitles = [NSMutableArray array];
            [categoryTitles addObject:@"全部"];
            for (int index = 0; index < _platformCategoryModel.sons.count; index ++)
            {
                XOPlatformCategoryModel *category = _platformCategoryModel.sons[index];
                
                [categoryTitles addObject:category.sortName?category.sortName:@""];
            }
            [self.segmentedControl setCategoryTitles:categoryTitles];
            self.segmentedControl.selectedIndex = 0;
        }
        _sortId = _platformCategoryModel.sortId;
    }
    self.segmentedControl.delegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHomeGoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"EJSHomeGoodCollectionViewCell"];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [self getGoodsList];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self getGoodsList];
    }];
    
    self.collectionView.mj_footer.automaticallyHidden = YES;
}

- (void)resetRequestData{
    _categoryId = _categoryModel.categoryId;
    _sortId = _platformCategoryModel.sortId;
    _order = nil;
    _currentPage = 1;
    [self updatePriceOrderImageView];
    [self updateOnSaleTimeOrderImageView];
    
}

- (void)updatePriceOrderImageView{
    if ([_order isEqualToString:@"priceAsc"]){
        _priceDescImageView.image = [UIImage imageNamed:@"lower_icon"];
    }else if ([_order isEqualToString:@"priceDesc"]){
        _priceDescImageView.image = [UIImage imageNamed:@"lower1_icon"];
    }else{
        _priceDescImageView.image = [UIImage imageNamed:@"lower2_icon"];
    }
}

- (void)updateOnSaleTimeOrderImageView{
    if ([_order isEqualToString:@"onsaleAsc"]){
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower_icon"];
    }else if ([_order isEqualToString:@"onsaleDesc"]){
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower1_icon"];
    }else{
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower2_icon"];
    }
}

- (void)getGoodsList{
    BaseRequest *request = nil;
    if(_keyWord){
      EJSSearchGoodsRequest *req = [EJSSearchGoodsRequest new];
        req.keyword = _keyWord;
        req.order = _order;
        req.page = @(_currentPage).stringValue;
        req.pageLimit = @"20";
        
        request = req;
    }else{
        EJSGoodsListRequest *req = [EJSGoodsListRequest new];
        req.categoryId = _categoryId;
        req.order = _order;
        req.page = @(_currentPage).stringValue;
        req.pageLimit = @"20";
        req.labelId = nil;
        req.sortId = _sortId;
        request = req;
    }
    FlyWeakSelf
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        EJSGoodsListModel *listModel = response.data;
        if(listModel){
            if(listModel.totalPages.integerValue == listModel.page.integerValue){
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            if(_currentPage == 1){
                weakSelf.goodsList = [NSMutableArray arrayWithArray:listModel.list];
            }else{
                [weakSelf.goodsList addObjectsFromArray:listModel.list];
            }
        }
        if(self.goodsList.count > 0){
            [self hideNoDataView];
        }else{
            [self showNoDataViewWithText:@"暂无商品数据"];
        }
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}
#pragma mark - EJSSegmentedControlDelegate
- (void)segmentedControl:(EJSSegmentedControl *)segmentedControl selectItemAtIndex:(NSUInteger)selectedIndex{
    if(_categoryModel){
        if(selectedIndex == 0){
            _categoryId = _categoryModel.categoryId;
        }else{
            EJSCategoryModel *model = self.categoryModel.sons[selectedIndex - 1];
            _categoryId = model.categoryId;
        }
    }
    if(_platformCategoryModel){
        if(selectedIndex == 0){
            _sortId = _platformCategoryModel.sortId;
        }else{
            XOPlatformCategoryModel *model = _platformCategoryModel.sons[selectedIndex - 1];
            _sortId = model.sortId;
        }
    }
    
    [self getGoodsList];
}
#pragma mark - Actions
- (IBAction)filterActin:(UIButton *)sender {
    _currentPage = 1;
    if(_currentSelectButton != sender){
        _currentSelectButton.selected = NO;
        sender.selected = YES;
        _currentSelectButton = sender;
        if (sender == self.defaultButton) {
            _order = nil;
        }else if (sender == self.salesButton){
            _order = @"";
        }
        else if (sender == self.priceButton){
            _order = @"priceAsc";
        }
        else if (sender == self.onSaleButton){
            _order = @"onsaleAsc";
        }
        [self updateOnSaleTimeOrderImageView];
        [self updatePriceOrderImageView];
        [self getGoodsList];
    }else{
        if (sender == self.priceButton){
            _order = [_order isEqualToString:@"priceAsc"]?@"priceDesc":@"priceAsc";
            [self updateOnSaleTimeOrderImageView];
            [self updatePriceOrderImageView];
            [self getGoodsList];
        }else if (sender == self.onSaleButton){
            _order = [_order isEqualToString:@"onsaleAsc"]?@"onsaleDesc":@"onsaleAsc";
            [self updateOnSaleTimeOrderImageView];
            [self updatePriceOrderImageView];
            [self getGoodsList];
        }
    }
}

#pragma mark - goosCellDelegate
- (BOOL)homeGoodCellIsLogin {
    return [self userIsLogin];
}

- (void)homeGoodUpdateShopCartWith:(EJSShoppingCartListModel *)cartListModel {
    self.shoppingCartListModel = cartListModel;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.goodsList.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSHomeGoodCollectionViewCell *goodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHomeGoodCollectionViewCell" forIndexPath:indexPath];
    EJSGoodsModel *model = self.goodsList[indexPath.item];
    goodsCell.delegate = self;
    goodsCell.goodModel = model;
    goodsCell.shoppingCartListModel = self.shoppingCartListModel;
    goodsCell.borderColor = UIColorFromRGB(0xE9E9E9);
    goodsCell.borderWidth = 0.5;

    return goodsCell;
}

- (void)shopCartGoodsCell:(EJSGoodsCCell *)cell addGoodsNum:(EJSGoodsModel *)model {
    [self getGoodsDetailInfo:model.spuId];
    
}

#pragma mark - Request

#pragma mark - loadData
- (void)getCartList{
    FlyWeakSelf
    EJSShoppingCartListRequest *req = [EJSShoppingCartListRequest new];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.shoppingCartListModel = response.data;
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage: response.message];
    }];
}

    //MARK:- 添加到购物车 (先获取详情)
- (void)getGoodsDetailInfo:(NSString *)goodId{
    EJSGoodsDetailInfoRequest *req = [EJSGoodsDetailInfoRequest new];
    req.spuId = goodId;
    FlyWeakSelf;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf addToShoppingCartAction:response.data];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)addToShoppingCartAction:(EJSGoodsModel *)detaiModel {
    if([self userIsLogin]){
        if(detaiModel.hasDefaultSku.integerValue == 1 && detaiModel.skus.count > 0){
            self.selectSkuModel = detaiModel.skus.firstObject;
            self.selectSkuModel.skuSelectCount = detaiModel.minToBuy.integerValue;
            [self addToCartReq:self.selectSkuModel];
            return;
        }
        FlyWeakSelf
        [EJSSelectGoodsSpecView showSelectGoodsSpecView:detaiModel completion:^(EJSGoodsSkuModel *selectSkuModel) {
            [weakSelf addToCartReq:selectSkuModel];
        }];
    }
}

- (void)addToCartReq:(EJSGoodsSkuModel *)skuModel{
    EJSGoodsAddCartRequest *req = [EJSGoodsAddCartRequest new];
    req.skuId = skuModel.skuId;
    req.num = @(skuModel.skuSelectCount).stringValue;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"加入购物车成功"];
        if(weakSelf.selectSkuModel){
            weakSelf.selectSkuModel = nil;
        }
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (ScreenWidth - 0)/2;
    CGFloat height = 170 + ScreenWidth/2.0 * (300/375.0);
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] initWithNibName:@"EJSGoodsDetailInfoViewController" bundle:nil];
    goodsDetailVC.goodsId = [self.goodsList[indexPath.item] spuId];
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}
@end
